package cn.study.zgm.nettyall.selector.selector;

import javafx.beans.binding.StringBinding;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * packageName cn.study.zgm.nettyall.selector.selector
 *
 * @author 你的名字
 * @version JDK 8
 * @className TestSelectorBigDataBufferWrite (此处以class为例)
 * @date 2025/2/27
 * @description TODO
 */
@Slf4j
public class TestSelectorBigDataBufferWrite {
    public static void main(String[] args) throws IOException {
        final ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress("127.0.0.1",8081));
        ssc.configureBlocking(false);

        final Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT,null);

        while (true){
            selector.select();
            final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                final SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()){
                    final ServerSocketChannel ssChannel = (ServerSocketChannel) key.channel();
                    final SocketChannel sChannel = ssChannel.accept();
                    sChannel.configureBlocking(false);


                    StringBuilder sb = new StringBuilder();
                    for (int i = 3000000; i > 0; i--) {
                        sb.append("a");
                    }
                    ByteBuffer byteBuffer = Charset.defaultCharset().encode(sb.toString());
                    final SelectionKey sKey = sChannel.register(selector, SelectionKey.OP_READ, null);
                    int write = sChannel.write(byteBuffer);
                    System.out.println(write);
                    if (byteBuffer.hasRemaining()){
                        sKey.interestOps(sKey.interestOps()+SelectionKey.OP_WRITE);
                        sKey.attach(byteBuffer);
                    }
                }else if (key.isWritable()){
                    ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
                    SocketChannel sChannel = (SocketChannel) key.channel();
                    final int write = sChannel.write(byteBuffer);
                    System.out.println("打印："+write);
                    if (!byteBuffer.hasRemaining()){
                        // 移除附件
                        key.attach(null);
//                        sChannel.op
                        key.interestOps(key.interestOps()-SelectionKey.OP_WRITE);
                    }
                }
            }
        }

    }
}
